/**
 * 
 */
package optimization.naturalOptimization.fitness;

import multithreading.FitnessCalculator;
import optimization.naturalOptimization.population.Population;

/**
 * Test fitness function to test algorithms for the behavior in flat fitness landscapes. 
 * The minimum position for this fitness function is 0.3 in uneven dimensions und 0.7 in even dimensions.
 * 
 * @author Kevin Wagner
 * @version 1.0
 */
public class CircleBoundCheck extends SimpleFitnessFunction<double[]> {

	private Population pop;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * optimization.naturalOptimization.fitness.SimpleFitnessFunction#getFitness
	 * (java.lang.Object)
	 */
	@Override
	public double getFitness(double[] position) {
		double erg = 0.0;
		for (int i = 0; i < (position.length/2); i++) {
			double a=position[2*i];
			double b=position[2*1+1];
			double distance=Math.sqrt(Math.pow(a-0.3, 2.0)+Math.pow(b-0.7, 2.0));
			if(distance<0.3){
				erg-=1.0;
			}
		}
		double[][] bounds = ((double[][]) pop.getParentOptimization()
				.getBoundaries());
		if (bounds != null) {
			double temp = 0.0;
			for (int i = 0; i < position.length; i++) {
				if (position[i] < bounds[i][0]) {
					temp += 10.0 * (Math.abs(position[i] - bounds[i][0]));
				} else if (position[i] > bounds[i][1]) {
					temp += 10.0 * (Math.abs(position[i] - bounds[i][1]));
				}
			}
			erg+=temp;//Strafterm
		}
		return erg;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see optimization.IdentificationI#getIndentification()
	 */
	@Override
	public String getIndentification() {
		return "Test Function: CircleBoundCheck";
	}

	@Override
	public void getFitness(Population pop) throws Exception {
		this.pop = pop;
		int ind = pop.getNumberOfIndividuals();
		FitnessCalculator[] calculators = new FitnessCalculator[ind];
		for (int i = 0; i < ind; i++) {
			calculators[i] = new FitnessCalculator(pop.getIndividual(i), this);
			calculators[i].start();
		}
		for (int i = 0; i < ind; i++) {
			calculators[i].join();
		}
	}

}
